<?php

namespace Addons\IntegralShop\Repositor;

use Addons\IntegralShop\Model\IsUserModel;

class IsUserRepositor extends BaseRepositor
{
    private $model;

    public function __construct()
    {
        $this->model = new IsUserModel();
    }

    /**
     * 获取当前用户积分
     * @return array|int|mixed|string
     */
    public function getCurUserMark()
    {
        $mark = $this->model->where([
            'openid' => get_openid()
        ])->getField("mark");

        return is_null($mark) ? -1 : $mark;
    }

    /**
     * 初始化用户信息
     * @return bool
     */
    public function init()
    {
        $openid = get_openid();
        $userInfo = $this->model->getByOpenid($openid);

        // 用户信息已存在
        if (!empty($userInfo)) return true;

        // 添加一条用户信息
        if (!$this->model->add([
            'openid' => $openid,
            'mpid' => get_mpid(),
            'mark' => 0,
            'total_mark' => 0
        ])) {
            $this->errMsg = "服务器错误";
            return false;
        }

        return true;
    }

    /**
     * 给用户添加推广奖励
     * @param $unId
     * @return bool
     */
    public function addMark2Un($unId)
    {
        $fanId = str2Int($unId);
        $fansInfo = M('mp_fans')->where(['id' => $fanId, 'mpid' => get_mpid()])->find();

        // 用户不存在或者是本人
        if (empty($fansInfo) || $fansInfo['openid'] == get_openid()) return false;

        // 添加积分
        $config = get_addon_settings();
        $config || $config = [];
        $addMark = isset($config['spread']['spread_mark_per_time']) ? $config['spread']['spread_mark_per_time'] : 0;
        while (!$this->updateUserMark($fansInfo["openid"], $addMark)) {

        };

        // 添加积分操作记录
        $recordRepo = new IsSpreadsRecordRepositor();
        $eventContent = "推广公众号";
        $recordRepo->add($fansInfo['openid'], IsSpreadsRecordRepositor::EVENT_TYPE_SPREAD, $eventContent, IsSpreadsRecordRepositor::OP_TYPE_ADD, $addMark);

        return true;
    }

    /**
     * 更新用户积分
     * @param $openid
     * @param $mark
     * @return bool|int|string
     */
    public function updateUserMark($openid, $mark,$needAddTotal = true)
    {
        $userMarkInfo = $this->model->getByOpenid($openid);

        $data['mark'] = $userMarkInfo["mark"] + $mark;
        $needAddTotal && $data['total_mark'] = $userMarkInfo["total_mark"] + $mark;


        return $this->model->where([
            "openid" => $openid,
            "mark" => $userMarkInfo["mark"],
            "total_mark" => $userMarkInfo["total_mark"],
        ])->save($data);
    }
}
